<?php

namespace App\Libs;


class Jidi {

    private $_base_url = 'http://newapi.tkjidi.com';
    private $_access_token_url = '/api/partner/getAccessToken'; //获取token
    private $_refulsh_token_url = '/api/partner/refreshAccessToken'; // 刷新token
    private $_products_url = '/api/partner/getProducts'; //获取基地商品列表
    private $_product_url = '/api/partner/getProductInfo'; //获取商品详情
    private $_convert_url = '/api/partner/speedConvertUrl'; //高效转链接
    private $_category_url = '/api/partner/getCategories'; //获取分类列表

    private $_username;
    private $_password;

    private $_accessToken;

    public function getToken(){
        $this->_username = env('JIDI_USERNAME');
        $this->_password = env('JIDI_PASSWORD');

        $tokenCache = \Cache::get('jidi-access-token');
        \Log::debug(json_encode($tokenCache));
        if(empty($tokenCache)) {
            $postData = [
                'username' => $this->_username,
                'password' => $this->_password
            ];
            $jidiData = curlPost($this->_base_url . $this->_access_token_url, $postData);
            $jidiData = json_decode($jidiData);
            if ($jidiData && !isset($jidiData->error)) {
                $this->accessToken = $jidiData->data->token;
                \Cache::put('jidi-access-token', $jidiData->data, $jidiData->data->expired_time / 60);
            }else{
                \Log::error('获取token失败'.json_encode($jidiData));
            }
        }else{
            $time = time();
            if(strtotime($tokenCache->expired_at) < $time){
                \Log::info('刷新基地token');
                $reJidiData = curlPost($this->_base_url . $this->_refulsh_token_url, ['token' => $tokenCache->token]);
                $reJidiData = json_decode($reJidiData);
                if (!isset($reJidiData->error)) {
                    $this->_accessToken = $reJidiData->data->token;
                    \Cache::put('jidi-access-token', $reJidiData->data, $reJidiData->data->refresh_expired_time / 60);
                }
            }else{
                $this->_accessToken = $tokenCache->token;
            }
        }
        return $this->_accessToken;
    }

    public function getProductUrl(){
        return $this->_base_url.$this->_product_url;
    }

    public function getProductsUrl(){
        return $this->_base_url.$this->_products_url;
    }

    public function getConvertUrl(){
        return $this->_base_url.$this->_convert_url;
    }

    public function getCategoryUrl(){
        return $this->_base_url.$this->_category_url;
    }
}